package com.matt.service.courseV2.impl;

import com.dotflat.xj.domain.Data;
import com.dotflat.xj.repository.DataRepository;
import com.matt.commons.exception.BusinessException;
import com.matt.domain.Children;
import com.matt.domain.Classes;
import com.matt.domain.courseV2.Ability;
import com.matt.domain.courseV2.AbilityUser;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.model.MemVerificationCache;
import com.matt.foundation.utils.DateUtil;
import com.matt.repository.ChildrenRepository;
import com.matt.repository.ClassesRepository;
import com.matt.repository.base.BaseNativeSqlRepository;
import com.matt.repository.courseV2.AbilityRepository;
import com.matt.repository.courseV2.AbilityUserRepository;
import com.matt.service.courseV2.AbilityService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class AbilityServiceImpl implements AbilityService {

    @Autowired
    private AbilityRepository abilityRepository;

    @Autowired
    private AbilityUserRepository abilityUserRepository;

    @Autowired
    private BaseNativeSqlRepository baseNativeSqlRepository;

    @Autowired
    private ChildrenRepository childrenRepository;

    @Autowired
    private ClassesRepository classesRepository;

    @Autowired
    protected MemVerificationCache cache;

    @Autowired
    private DataRepository dataRepository;

    @Override
    public Map list(String childrenId, String timeAxis,String name, String states, String completeStates) {

        String sql = String.format("SELECT a.`name`,a.startTime,IFNULL(au.url,'') url,IFNULL(au.childrenId,'') childrenId, " +
                "IFNULL(au.created,''),IFNULL(au.states,'') states   " +
                " ,IFNULL(au.childrenTime,'') childrenTime ,IFNULL(c.`name`,'')  childrenName,IFNULL(au.id,'') id   " +
                " FROM tc_ability  a LEFT JOIN  tc_ability_user au ON  a.id =  au.milepostId LEFT JOIN  children c on au.childrenId = c.id " +
                " and  au.childrenId    = '%s'  where 1=1 ",childrenId );

        if (Objects.nonNull(timeAxis)) {
            sql += String.format(" and a.timeAxis  = '%s' ", timeAxis);
        }

        if (Objects.nonNull(name)) {
            sql += " and a.`name`  LIKE  concat('%', '"+name+"', '%')";
        }
        if (Objects.nonNull(states)) {
            if (StringUtils.equals(states,"0")){
                sql += String.format(" and au.states  ='%s' ", states);
            }else {
                sql += " and au.states  >0 ";
            }
        }

        if (Objects.nonNull(completeStates)) {
            sql += String.format(" and au.states   ='%s' ", completeStates);
        }
        List<Object[]> objects = baseNativeSqlRepository.sqlArrayList(sql);
        List<Map> mapList = new ArrayList<>();
        for (int i = 0; i < objects.size(); i++) {
            Map map = new HashMap();
            map.put("name", objects.get(i)[0].toString());
            map.put("startTime", objects.get(i)[1].toString());
            map.put("url", objects.get(i)[2].toString());
            map.put("childrenId", objects.get(i)[3].toString());
            map.put("created", objects.get(i)[4].toString());
            map.put("states", objects.get(i)[5].toString());
            map.put("childrenTime", objects.get(i)[6].toString());
            map.put("childrenName", objects.get(i)[7].toString());
            map.put("id", objects.get(i)[8].toString());
            mapList.add(map);
        }
        Map map = new HashMap();
        map.put("total",objects.size());
        map.put("list",mapList);
        return map;
    }

    @Override
    public AbilityUser add(String childrenId, String abilityId, String url) {
        Children children = childrenRepository.findByCrmClienteleId(childrenId);
        if (Objects.isNull(children)){
            throw  new BusinessException(ErrorCode.IS_TARGET, "对象不存在");
        }
        Ability ability  = abilityRepository.getOne(abilityId);
        if (Objects.isNull(ability)){
            throw  new BusinessException(ErrorCode.IS_TARGET, "对象不存在");
        }

        //出生到现在的月与天
        String m = DateUtil.birthdayMonthDay(new Date(),children.getBirthday());
        //出生到现在的总天数
        int day  =DateUtil.birthdayDay(new Date(),children.getBirthday()) +1;
        AbilityUser abilityUser = new AbilityUser();
        abilityUser.setMilepostId(ability.getId());
        abilityUser.setChildrenTime(m);
        abilityUser.setChildrenId(childrenId);
        abilityUser.setUrl(url);
        String states;
        if (ability.getStartTime() <= day && ability.getEndTime()  >= day){
            states = "1";
        }else if (ability.getStartTime()  > day){
            states = "2";
        }else {
            states = "3";
        }
        abilityUser.setStates(states);
        abilityUserRepository.save(abilityUser);
        return abilityUser;
    }



    @Override
    public List<Map> timeList(String time) {
        String sql = "SELECT id,name    FROM  tc_ability " +
                " where  DATE_FORMAT(startTime,'%Y-%m-%d %H:%i:%S' )  >=  DATE_FORMAT('"+time+" 00:00:00"+"','%Y-%m-%d %H:%i:%S') " +
                " and  DATE_FORMAT(endTime,'%Y-%m-%d %H:%i:%S' )  <=  DATE_FORMAT('"+time+" 23:59:59"+"','%Y-%m-%d %H:%i:%S')";
        List<Object[]> objects = baseNativeSqlRepository.sqlArrayList(sql);
        List<Map> mapList = new ArrayList<>();
        for (int i = 0; i < objects.size(); i++){
            Map map = new HashMap();
            map.put("id", objects.get(i)[0].toString());
            map.put("name", objects.get(i)[1].toString());
            mapList.add(map);
        }
         return mapList;
    }



    @Override
    public List<Map> timeAxis() {
        String sql = " SELECT IFNULL(timeAxis,'') timeAxis   FROM  tc_ability  GROUP BY timeAxis ";
        List<Object[]> objects = baseNativeSqlRepository.sqlArrayList(sql);
        List<Map> mapList = new ArrayList<>();
        for (int i = 0; i < objects.size(); i++){
            Map map = new HashMap();
            map.put("timeAxis", objects.get(i));
            mapList.add(map);
        }
        return mapList;
    }

    @Override
    public  List<Map> monthCount(String childrenId, String time) {

        List<Data> dataList =  dataRepository.findAllByType("tc_ability_label");
        List<Data> dataList1 =  dataRepository.findAllByType("tc_ability_item");

        String sql = "SELECT a.label,a.item,au.states   FROM tc_ability_user au LEFT JOIN tc_ability a on a.id = au.milepostId " +
                " LEFT JOIN children c on au.childrenId = c.id  " +
                " WHERE DATE_FORMAT(au.created,'%Y-%m-%d %H:%i:%S' )  >= DATE_FORMAT('"+time+"-01 00:00:00','%Y-%m-%d %H:%i:%S') " +
                " AND DATE_FORMAT(au.created,'%Y-%m-%d %H:%i:%S' )  <=   DATE_FORMAT('"+time+"-31 23:59:59','%Y-%m-%d %H:%i:%S') ";

        sql += String.format(" and au.childrenId  ='%s' ", childrenId);

        List<Object[]> objects = baseNativeSqlRepository.sqlArrayList(sql);
        List<Map> mapList = new ArrayList<>();

        for (int i = 0; i <dataList.size() ; i++) {
            Map map = new HashMap();
            map.put("label",dataList.get(i).getLabel());
            int count = 0 ;
            List<Map> list1 = new ArrayList<>();

            for (int j = 0; j < dataList1.size(); j++) {
                Map map1 = new HashMap();
                int number = 0 ;
                map1.put("item",dataList1.get(j).getLabel());
                for (int k = 0; k <objects.size() ; k++) {
                    String label = objects.get(k)[0].toString();
                    String item = objects.get(k)[1].toString();
                    if (StringUtils.equals(dataList.get(i).getVal(),label) && StringUtils.equals(dataList.get(j).getVal(),item)){
                        number++;
                        count++;
                    }
                }
                map1.put("number",number);
                list1.add(map1);
            }


            List<Map> list2 = new ArrayList<>();
            for (int j = 0; j <3 ; j++) {
                int number = 0;
                Map map1 = new HashMap();
                if (j==0){
                    map1.put("states","应达成");
                }else if (j==1){
                    map1.put("states","已达成");
                }else {
                    map1.put("states","超前");
                }
                for (int k = 0; k <objects.size() ; k++) {
                    String label = objects.get(k)[0].toString();
                    String states = objects.get(k)[2].toString();
                    if (j==1){
                        if (StringUtils.equals(dataList.get(i).getVal(),label) && (StringUtils.equals(String.valueOf(1),states) || StringUtils.equals(String.valueOf(3),states)) ){
                            number++;
                        }
                    }else {
                        if (StringUtils.equals(dataList.get(i).getVal(),label) && StringUtils.equals(String.valueOf(j),states)){
                            number++;
                        }
                    }
                }
                map1.put("number",number);
                list2.add(map1);
            }
            map.put("list",list1);
            map.put("statesList",list2);
            map.put("number",count);
            mapList.add(map);
        }
        return mapList;
    }

    @Override
    public void addAll(List<Ability> abilityList) {
        abilityRepository.saveAll(abilityList);
    }
}
